import styles from './Texting.module.scss'

import { getCustomeSmsSignList, getCustomeSmsTemplateList, getCustomeSmsSend, getCustomeSmsAuthSso } from '@/api/customer/manage/list'

import { ElForm, ElFormItem, ElSelect, ElOption, ElLink, ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import Dialog from '@/components/Dialog.vue'
import { defineComponent, ref, reactive, watch, toRefs, onMounted } from 'vue'
import { useExpose } from '@/components/zw/utils'
import _ from 'lodash'

export default defineComponent({
  name: 'Texting',
  props: {
    phoneList: {},
    touchMobile:{}
  },
  setup(props, { emit, slots }) {
    const { phoneList } = toRefs(props)
    const { touchMobile } = toRefs(props)
    console.log(touchMobile.value?.phone,'touchMobiletouchMobiletouchMobiletouchMobile');
    
    const cancelHandel = () => {
      appDialog.visible = false
      formRef.value.resetFields()
    }
    const submitHandel = async () => {
      if (!formRef.value) return
      await formRef.value.validate((valid: any, fields: any) => {
        if (valid) {
          getCustomeSmsSend(form).then((res) => {
            ElMessage.success('发送成功')
            appDialog.visible = false
          })
        } else {
          console.log('error submit!', fields)
        }
      })
    }

    const appDialog = reactive({
      visible: false,
      title: '',
      width: '600px',
      cancel: cancelHandel,
      submit: submitHandel,
      cancelText: '取消',
      submitText: '发送'
    })
    const state = reactive({
      signList: [],
      templateList: [],
      phoneData: []
    })
    const formRef = ref<FormInstance>(null)
    const form = reactive({
      cust_id: '',
      sign_id: '',
      template_id: '',
      send_mobile: ''
    })
    const rules = reactive<FormRules>({
      sign_id: [{ required: true, message: '请选择签名', trigger: 'change' }],
      send_mobile: [{ required: true, message: '请选择手机号', trigger: 'change' }],
      template_id: [{ required: true, message: '请选择模板', trigger: 'change' }]
    })
    const onTexting = (data: any) => {
      let params = {
        sign_name: '',
        state: 2
      }
      form.cust_id = data.cust_id
      getCustomeSmsSignList(params).then((res: any) => {
        state.signList = res.result
        const index = res.result.find((item: any) => item.id == res.before_use_id)
        if (res.before_use_id && index != -1) {
          form.sign_id = res.before_use_id
          onChangeSign()
        }
      })
      appDialog.visible = true
      const { name, nickname, mobile } = data.baseInfo
      appDialog.title = `发短信给客户【${name || nickname || mobile}】`
    }
    const onChangeSign = () => {
      form.template_id = ''
      let parmas = {
        sign_id: form.sign_id,
        state: 2,
        page: 1,
        page_size: 1000
      }
      getCustomeSmsTemplateList(parmas).then((res: any) => {
        state.templateList = res.data
      })
    }
    const toAuthList = (num: any) => {
      getCustomeSmsAuthSso({ module: num }).then((res: any) => {
        window.open(res.sso_url)
      })
    }
    const mergePhone = (data: any, strArr: any) => {
      let result: any = []
      const indexArr = strArr.map((item: any) => {
        const i = data.filter((i: any) => i.name == item)
        return i
      })
      indexArr.map((item: any) => {
        if (item instanceof Array && item.length > 0) {
          item.map((i: any) => {
            if (i.val instanceof Array && i.val.length > 0) {
              i.val.map((n: any) => {
                result.push(n)
              })
            } else if (i.val != '') {
              const arr = i.val.split(',')
              arr.map((n: any) => {
                result.push(n)
              })
            }
          })
        }
      })
      return result
    }
    const desPhone = (data: any) => {
      const arr: any = []
      if (data && data.length > 0) {
        data.map((n: any) => {
          arr.push({ id: n.item ? n.item : n, value: n.item ? n.item.replace(/(\d{3})\d*(\d{4})/, '$1****$2') : n.replace(/(\d{3})\d*(\d{4})/, '$1****$2') })
        })
      }
      if (arr.length > 0) {
        form.send_mobile = arr[0].id
      }
      return arr
    }
    watch(
      () => phoneList.value,
      (val) => {
        // 主手机号 + 备用手机号
        let mobile = ''
        if(Array.isArray(touchMobile.value?.phone) && touchMobile.value?.phone.length>=1){
          mobile = touchMobile.value?.phone.map(v=>v.mobile)
        }
        const res = Array.from(new Set(mergePhone(val, ['企微手机号', '备用手机号'])))
        let arr =  res.concat(mobile)
        _.uniqWith(arr, _.isEqual)
        state.phoneData = desPhone(arr)
      }
    )
    useExpose({
      onTexting
    })
    return () => (
      <Dialog appDialog={appDialog}>
        <ElForm ref={formRef} model={form} rules={rules} labelWidth="82px" size="small">
          <ElFormItem label="手机号" prop="send_mobile">
            <ElSelect
              style="width:55%"
              vModel={form.send_mobile}
              placeholder="请选择手机号"
              vSlots={{
                default: () => (
                  <>
                    {state.phoneData.map((item: any) => (
                      <ElOption key={item.id} value={item.id} label={item.value} />
                    ))}
                  </>
                )
              }}
            />
          </ElFormItem>
          <ElFormItem label="短信签名" prop="sign_id">
            <ElSelect
              style="width:55%"
              vModel={form.sign_id}
              placeholder="请选择短信签名"
              onChange={onChangeSign}
              vSlots={{
                default: () => (
                  <>
                    {state.signList.map((item: any) => (
                      <ElOption key={item.id} value={item.id} label={item.sign_name} />
                    ))}
                  </>
                )
              }}
            />
            <span class={styles.sign}>
              签名不存在？
              <ElLink underline={false} type="primary" onClick={() => toAuthList(3)}>
                去申请
              </ElLink>
            </span>
          </ElFormItem>
          <ElFormItem label="短信模板" prop="template_id" showMessage={false}>
            <ElSelect
              style="width:55%"
              vModel={form.template_id}
              placeholder="请选择短信模板"
              disabled={!form.sign_id}
              vSlots={{
                default: () => (
                  <>
                    {state.templateList.map((item: any) => (
                      <ElOption key={item.id} value={item.id} label={item.template_name} />
                    ))}
                  </>
                )
              }}
            />
            <span class={styles.sign}>
              模板不存在？
              <ElLink underline={false} type="primary" onClick={() => toAuthList(4)}>
                去申请
              </ElLink>
            </span>
          </ElFormItem>
        </ElForm>
      </Dialog>
    )
  }
})
